package com.share.redisson.rest;

import com.share.redisson.lock.DistributeLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @desc: 分布式锁测试  参考：https://blog.csdn.net/HXNLYW/article/details/103069026
 * @author:caifan
 * @date:2020/4/19
 */
@RestController
@RequestMapping("/rest")
public class DistributeLockRest {
    @Autowired
    Environment environment;
    private int num1 = 10;
    private int num2 = 10;
    Lock lock = new ReentrantLock();

    @Autowired
    DistributeLock distributeLock;

    @GetMapping("/test")
    public String test() {
        return environment.getProperty("server.port");
    }

    @RequestMapping("/distributeLock")
    public void distributeLock() {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i=0;i<10;i++) {
            executorService.submit(() -> {
                sub1();
                System.out.println(num1);
            });
        }
        num1=10;
        System.out.println("========");
    }

    @RequestMapping("/localLock")
    public void lock() {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i=0;i<10;i++) {
            executorService.submit(() -> {
                sub2();
                System.out.println(num2);
            });
        }
        num2=10;
        System.out.println("______________");
    }


    public void sub1() {
        distributeLock.lock("test");
        num1--;
        distributeLock.unlock("test");
    }



    public void sub2() {
        lock.lock();
        num2--;
        lock.unlock();
    }
}
